import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/tab_model.dart';
import 'package:yysk_app/pages/login/lisence_widget.dart';
import 'package:yysk_app/pages/login/login_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/checkbox_widget.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/input_widget.dart';
import 'package:yysk_app/widget/tab_widget.dart';
import 'package:yysk_app/widget/verification_code_widet.dart';
import 'package:oktoast/oktoast.dart';

class LoginPage extends GetView<LoginController> {
  static const path = '/login';
  LoginPage({super.key});

  final List<TabModel> list = [
    TabModel(label: '验证码登录', code: 'phone'),
    TabModel(label: '密码登录', code: 'password'),
  ];

  // final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController _accountController = TextEditingController();
  final TextEditingController _account2Controller = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;

    return Scaffold(
      // key: _scaffoldKey,
      resizeToAvoidBottomInset: false,
      backgroundColor: AppColors.backgroundColorBlack,
      body: Obx(
        () =>
            Stack(children: [..._background(), ..._content(context: context)]),
      ),
    );
  }

  void hideKeyboard(BuildContext context) {
    FocusScopeNode currentFous = FocusScope.of(context);
    if (!currentFous.hasPrimaryFocus && currentFous.focusedChild != null) {
      FocusManager.instance.primaryFocus!.unfocus();
    }
  }

  _background() {
    return [
      Positioned.fill(
        top: 0.px,
        left: 0,
        child: ImageAssetWidget(
          imageUrl: 'static/images/bg2.png',
          width: 375.px,
          height: 812.px,
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
        ),
      ),
    ];
  }

  _content({required BuildContext context}) {
    return [
      Center(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
          child: Stack(
            children: [
              ListView(
                children: [
                  Container(
                    height: 258.px,
                    padding: EdgeInsets.only(top: 100.px),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ImageAssetWidget(
                          imageUrl: 'static/images/logo.png',
                          width: 83.px,
                          height: 83.px,
                          fit: BoxFit.fitWidth,
                          alignment: Alignment.topCenter,
                        ),
                        hiSpace(height: 20.px),

                        Text(
                          '欢迎注册/登录元宇时空',
                          style: TextStyle(
                            fontSize: 16.px,
                            color: AppColors.backgroundColor,
                          ),
                        ),
                        hiSpace(height: 6.px),

                        Text(
                          '未注册号码将自动创建账号',
                          style: TextStyle(
                            fontSize: 12.px,
                            color: AppColors.fontColorGray99,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.fromLTRB(24.px, 40.px, 24.px, 0),
                    child: Column(
                      children: [
                        Padding(
                          padding: EdgeInsets.only(left: 8.px),
                          child: TabWidget(
                            tabList: list,
                            onChanged: _onChange,
                            sign: true,
                            activeColor: AppColors.backgroundColor,
                            tabColor: AppColors.fontColorGray99,
                            currentUndelineColorStart: Color.fromRGBO(
                              0,
                              234,
                              255,
                              1,
                            ),
                            currentUndelineColorEnd: Color.fromRGBO(
                              0,
                              193,
                              242,
                              0.06,
                            ),
                            currentUndeline: true,
                          ),
                        ),
                        IndexedStack(
                          index: controller.current.value == 'password' ? 1 : 0,
                          children: [_codeLogin(context), _passwordLogin()],
                        ),

                        hiSpace(height: 48.px),
                        CheckboxWidget(
                          onChanged: controller.onReadChanged,
                          checked: controller.isRead.value,
                          label: LisenceWidget(
                            fontSize: 14,
                            color: AppColors.fontColorGray99,
                          ),
                        ),
                        hiSpace(height: 14.px),
                        ButtonWidget(
                          label: '登录',
                          height: 47.px,
                          width: 327.px,
                          fontSize: 16.px,
                          fontWeight: FontWeight.w500,
                          onPressed: () {
                            _handleLogin(context);
                          },
                        ),

                        // hiSpace(height: 6),
                        // ButtonWidget(
                        //   label: '跳主页',
                        //   height: 54.px,
                        //   width: 322.px,
                        //   fontSize: 22.px,
                        //   contentType: ContentType.other,
                        //   onPressed: () {
                        //     Get.toNamed(MainPage.path);
                        //   },
                        // ),
                        hiSpace(height: 200.px),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    ];
  }

  // 变更登录方式的时候，清理掉之前输入的账号密码
  void _onChange(String value) {
    print('${value}------${controller.account}------${controller.userTel}');
    if (value == 'phone' && controller.account.value!.isNotEmpty) {
      // 验证码登录
      _account2Controller.text = controller.account.value!;
      controller.userTel.value = controller.account.value!;
    }
    if (value == 'password' && controller.userTel.value.isNotEmpty) {
      // 验证码登录
      _accountController.text = controller.userTel.value;
      controller.account.value = controller.userTel.value;
    }
    controller.onTypeChanged(value);
    // _accountController.clear();
    // _codeController.clear();
  }

  Widget _passwordLogin() {
    return Column(
      children: [
        SizedBox(height: 10.px),
        InputWidget(
          hint: '请输入11位手机号码',
          controller: _accountController,
          backgroundColor: AppColors.backgroundColorBlackLight,
          buttonRadio: 24,
          errorText: controller.showPasswordErrorText.value ? '手机号输入错误' : null,
          inputType: TextInputType.number,
          onChanged: (value) {
            // print(value);
            // 验证是否为纯数字
            if (RegExp(r'^\d{0,11}$').hasMatch(value)) {
              // print('${value}===');
              controller.onValueChanged(
                value.length > 11 ? value.substring(0, 11) : value,
                'account',
              );
            } else {
              _accountController.value = TextEditingValue(
                text: '${controller.account.value}', // 截断到 11 位
                selection: TextSelection.collapsed(
                  offset: controller.account.value!.length,
                ), // 光标移动到末尾
              );
            }
          },
        ),
        hiSpace(height: 12.px),
        InputWidget(
          hint: '请输入登录密码',
          controller: _codeController,
          obscureText: true,
          backgroundColor: AppColors.backgroundColorBlackLight,
          buttonRadio: 24,
          visible: true,
          onChanged: (value) {
            controller.onValueChanged(value, 'password');
          },
        ),
        // Container(
        //   transform: Matrix4.translationValues(10.px, -20.px, 0),
        //   child: Row(
        //     mainAxisAlignment: MainAxisAlignment.end,
        //     children: [
        //       ButtonWidget(
        //         label: '忘记密码?',
        //         fontSize: 12,
        //         height: 17.px,
        //         width: 100.px,
        //         fontColor: AppColors.fontColorGreen,
        //         onPressed: () {
        //           Get.toNamed(ForgotPasswordPage.path);
        //         },
        //       ),
        //     ],
        //   ),
        // ),
      ],
    );
  }

  Widget _codeLogin(context) {
    return Column(
      children: [
        SizedBox(height: 10.px),
        InputWidget(
          hint: '请输入11位手机号码',
          buttonRadio: 24,
          controller: _account2Controller,
          errorText: controller.showCodeErrorText.value ? '手机号输入错误' : null,
          // title: '手机号',
          backgroundColor: AppColors.backgroundColorBlackLight,
          inputType: TextInputType.number,
          onChanged: (value) {
            // 验证是否为纯数字
            if (RegExp(r'^\d{0,11}$').hasMatch(value)) {
              // print('${value}===');
              controller.onValueChanged(
                value.length > 11 ? value.substring(0, 11) : value,
                'userTel',
              );
            } else {
              _account2Controller.value = TextEditingValue(
                text: controller.userTel.value, // 截断到 11 位
                selection: TextSelection.collapsed(
                  offset: controller.userTel.value.length,
                ), // 光标移动到末尾
              );
            }
          },
        ),
        hiSpace(height: 12.px),

        VerificationCodeWidet(
          type: VerificationCodeType.LOGIN,
          phoneNumber: controller.userTel.value,
          initialCount: 60,
          buttonRadio: 24,
          onChanged: _onCodeSubmit,
          hintText: '请输入验证码',
        ),
      ],
    );
  }

  void _handleLogin(context) {
    if (controller.isRead.value) {
      var phone;
      if (controller.current.value == 'password') {
        phone = controller.account.value;
      } else {
        phone = controller.userTel.value;
      }
      if (phone.length < 11) {
        if (controller.current.value == 'phone') {
          controller.showCodeErrorText.value = true;
        } else {
          controller.showPasswordErrorText.value = true;
        }
        // showToast('请输入正确的手机号');
      } else {
        controller.showCodeErrorText.value = false;
        controller.showPasswordErrorText.value = false;
        controller.submit();
      }
    } else {
      showToast('请阅读理解并同意协议');
      // _showSheet(context);
    }
  }

  void _showSheet(context) {
    showModalBottomSheet(
      context: context,
      isDismissible: true,
      enableDrag: false, // 禁止拖拽，否则报错
      builder: (BuildContext context) {
        return BottomSheet(
          onClosing: () {},
          enableDrag: false, // 禁止拖拽，否则报错
          builder: (BuildContext context) {
            return Container(
              height: 206,
              width: MediaQuery.of(context).size.width,
              color: Colors.white,
              child: Padding(
                padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
                child: Column(
                  children: [
                    Align(
                      alignment: Alignment.centerRight,
                      child: IconButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        icon: Icon(Icons.close_outlined, size: 24.px),
                      ),
                    ),
                    hiSpace(height: 10),
                    LisenceWidget(fontSize: 12),
                    hiSpace(height: 32),
                    ButtonWidget(
                      label: '同意',
                      onPressed: () {
                        controller.onReadChanged(true);
                        // controller.submit();
                        Navigator.of(context).pop();
                      },
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  _onCodeSubmit({String? code, int? msgId}) {
    if (code != null && code != '') {
      controller.onValueChanged(code, 'code');
    }
    controller.onValueChanged(msgId, 'smsId');
  }
}
